package com.bcmusic.user.service.impl;

import com.bcmusic.user.dao.UserMapper;
import com.bcmusic.user.pojo.User;
import com.bcmusic.user.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import entity.BCrypt;
import entity.HttpUtils;
import entity.Result;
import entity.VerificationCode;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/****
 * @Author:admin
 * @Description:User业务层接口实现类
 * @Date 2019/6/14 0:16
 *****/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * User条件+分页查询
     *
     * @param user 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public PageInfo<User> findPage(User user, int page, int size) {
        //分页
        PageHelper.startPage(page, size);
        //搜索条件构建
        Example example = createExample(user);
        //执行搜索
        return new PageInfo<User>(userMapper.selectByExample(example));
    }

    /**
     * User分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<User> findPage(int page, int size) {
        //静态分页
        PageHelper.startPage(page, size);
        //分页查询
        return new PageInfo<User>(userMapper.selectAll());
    }

    /**
     * User条件查询
     *
     * @param user
     * @return
     */
    @Override
    public List<User> findList(User user) {
        //构建查询条件
        Example example = createExample(user);
        //根据构建的条件查询数据
        return userMapper.selectByExample(example);
    }


    /**
     * User构建查询对象
     *
     * @param user
     * @return
     */
    public Example createExample(User user) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (user != null) {
            // 用户id。
            if (!StringUtils.isEmpty(user.getUserId())) {
                criteria.andEqualTo("userId", user.getUserId());
            }
            // 用户编号。注册年份4位+注册编号8位，例如，
            if (!StringUtils.isEmpty(user.getUserNumber())) {
                criteria.andEqualTo("userNumber", user.getUserNumber());
            }
            // 用户电话。手机号是注册账号。
            if (!StringUtils.isEmpty(user.getUserPhone())) {
                criteria.andEqualTo("userPhone", user.getUserPhone());
            }
            // 登陆密码。加密保存。
            if (!StringUtils.isEmpty(user.getPassword())) {
                criteria.andEqualTo("password", user.getPassword());
            }
            // 认证状态。0（false）为未认证，1（true）为已认证。注册时默认为未认证。
            if (!StringUtils.isEmpty(user.getIsValid())) {
                criteria.andEqualTo("isValid", user.getIsValid());
            }
            // 身份类型。00默认为普通用户，01为独立音乐人，02为商业使用企业，03为分发商，04为管理员。
            if (!StringUtils.isEmpty(user.getUserType())) {
                criteria.andEqualTo("userType", user.getUserType());
            }
            // 注册时间。
            if (!StringUtils.isEmpty(user.getRegisterTime())) {
                criteria.andEqualTo("registerTime", user.getRegisterTime());
            }
            // 最后修改时间。默认为注册时间。认证状态和身份类型仅可修改一次，登陆密码可多次修改。
            if (!StringUtils.isEmpty(user.getModifyTime())) {
                criteria.andEqualTo("modifyTime", user.getModifyTime());
            }
            //
            if (!StringUtils.isEmpty(user.getUserIdentiId())) {
                criteria.andEqualTo("userIdentiId", user.getUserIdentiId());
            }
        }
        return example;
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        userMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改User
     *
     * @param user
     */
    @Override
    public void update(User user) {
        userMapper.updateByPrimaryKey(user);
    }

    /**
     * 动态更改user
     */
    @Override
    public void updateSelective(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public String getVerificationCode(String phone) {
        String host = "http://yzx.market.alicloudapi.com";
        String path = "/yzx/sendSms";
        String method = "POST";
        String appcode = "2daa04e7ddf24cd191cf74e8d89df3b2";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        String code = VerificationCode.getrandom();
        querys.put("param", "code:" + code);
        querys.put("tpl_id", "TP1710262");
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(EntityUtils.toString(response.getEntity()));
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 增加User
     *
     * @param user
     */
    @Transactional
    @Override
    public User add(User user) {

        user.setPassword(passwordEncoder.encode(user.getPassword()));
        String userNum = userMapper.selectMaxUserNum();
        //暂时加一吧0.0.0.0，这个字段是真的烦。。。
        user.setUserNumber(String.valueOf(Long.valueOf(userNum)+1));
        userMapper.insertSelective(user);
        return userMapper.selectByPrimaryKey(user.getUserId());
    }

    /**
     * 根据ID查询User
     *
     * @param id
     * @return
     */
    @Override
    public User findById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询User全部数据
     *
     * @return
     */
    @Override
    public List<User> findAll() {
        return userMapper.selectAll();
    }

    @Override
    public User findUserByNum(String userNum) {
        return userMapper.selectUserByNum(userNum);
    }


}
